package com.yang.service.Impl;



import com.yang.domain.Result;
import com.yang.domain.VO.BlogUserLoginVo;
import com.yang.domain.VO.UserInfoVo;
import com.yang.domain.entity.LoginUser;
import com.yang.domain.entity.User;
import com.yang.utils.BeanCopyUtils;
import com.yang.utils.JwtUtil;
import com.yang.utils.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.yang.service.BlogLoginService;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.yang.constants.RedisConstants.BLOG_LOGIN;

/**
 * <p>
 * 前台登录实现类
 * </p>
 * @author yang
 * @date 2023/5/29
 */
@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Resource
    private RedisCache redisCache;

    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public Result login(User user) {
        //1.创建authenticationManager认证需要的实现类,将要进行认证的信息封装进去
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());

        //2.调用接口中authenticationManager的认证方法，回去调用我们自定义的UserDetailsService的方法进行认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //3.认证失败
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        //4.认证成功，从authenticate获取到用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();

        //5.把用户信息存入到redis里面
        redisCache.setCacheObject(BLOG_LOGIN+userId,loginUser,10, TimeUnit.MINUTES);

        //6.生成token,并且把user信息和token封装返回
        String jwt = JwtUtil.createJWT(userId);
        //user--->userInfoVo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        //userInfoVo+jwt--->BlogUserLoginVo
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt,userInfoVo);

        //7.返回给前端
        return Result.okResult(blogUserLoginVo);
    }

    @Override
    public Result logout() {
        //1.从securityContextHolder解析获取userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        //2.获取userid
        Long userId = loginUser.getUser().getId();

        //3.删除redis中的用户信息
        redisCache.deleteObject(BLOG_LOGIN+userId);

        return Result.okResult();
    }
}
